package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.*;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
@Slf4j
public class DishServiceImpl implements DishService {

    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    //新增菜品
    //需要同时增加菜品信息和口味信息,使用逻辑外键相连
    // dish_flavor(dish_id)->dish(id)
    @Override
    @Transactional//因为要同时操作两个表,要开启注解事务管理
    public void addDishWithFlavor(DishDTO dishDTO) {
        log.info("新增菜品和口味数据");
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //向菜品表插入1条数据
        dishMapper.addDish(dish);
        //向口味表插入n条数据
        Long id = dish.getId();//获取insert语句生成的主键值
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(id));
            dishFlavorMapper.addDishFlavor(flavors);
        }
    }

    //分页查询
    @Override
    public PageResult getAllDish(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        Page<DishVO> dishPage = dishMapper.getAllPage(dishPageQueryDTO);
        return new PageResult(dishPage.getTotal(), dishPage.getResult());
    }

    //依据id批量删除菜品数据
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
       /*
       //判断当前菜品能否被删除
        //是否是在售的商品
        ids.forEach(id -> {
            if (dishMapper.getById(id).getStatus().equals(StatusConstant.DISABLE))
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
        });
        //是否关联套餐
        ids.forEach(id -> {
            if (categoryMapper.getCategoryById(dishMapper.getById(id).getCategoryId()).getType().equals(2)){
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });
        //删除菜品数据和口味数据
        List<Long> list = new ArrayList<>();
        ids.forEach(id -> {
            list.add(dishMapper.getById(id).getId());
        });
        dishFlavorMapper.deleteDishFlavor(list);
        dishMapper.deleteDish(ids);
        */


        for (Long id : ids) {
            Dish dish = dishMapper.getById(id);
            if (dish == null) {
                continue; // 处理菜品不存在的情况
            }
            // 是否是在售的商品
            if (dish.getStatus() != null && dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }
        Integer setmealId = setmealDishMapper.getSetmealIdByDishIds(ids);
        if (setmealId != null && setmealId > 0) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        // 删除菜品数据和口味数据
        dishFlavorMapper.deleteDishFlavor(ids);
        dishMapper.deleteDish(ids);

    }


    //更改菜品可售卖状态,同时更改套餐的售卖状态
    @Override
    public void updateDishStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();//Build注解下可以进行链式编程
        dishMapper.updateDishStatus(dish);

        //停售操作,同时应当也将包含当前菜品的套餐也停售
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            List<Long> dishIds = new ArrayList<>();
            dishIds.add(id);
            List<Long> setmealIds = setmealDishMapper.getSetmealIdByDishIdsObj(dishIds);
            if (setmealIds != null && !setmealIds.isEmpty()) {
                for (Long setmealId : setmealIds) {
                    Setmeal setmeal = new Setmeal();
                    setmeal.setId(setmealId);
                    setmeal.setStatus(StatusConstant.DISABLE);
                    setmealMapper.update(setmeal)
                    ;
                }
            }
        }
    }

    //依据id获取菜品
    @Override
    public DishVO selectById(Long id) {
        DishVO dishVO = new DishVO();
        Dish dish = dishMapper.getById(id);
        List<DishFlavor> dishFlavor = dishFlavorMapper.getById(id);
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavor);
        dishVO.setUpdateTime(LocalDateTime.now());
        return dishVO;
    }

    //依据分类id获取菜品
    @Override
    public List<Dish> getDishByCategoryId(Long categoryId) {
        return dishMapper.getDishByCategoryId(categoryId);
    }

    /**
     * 条件查询菜品和口味
     *
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getDishByCategoryId(dish.getCategoryId());

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.getById(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;

    }

    @Override
    @Transactional
    public void updateDishInfo(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        //删除原来的口味,添加新的口味
        dishFlavorMapper.deleteDishFlavorByDishId(dishDTO.getId());
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(flavor -> flavor.setDishId(dishDTO.getId()));
            dishFlavorMapper.addDishFlavor(flavors);
        }


        //更新菜品的信息
        log.info("更新菜品的信息有{}",dish);
        dishMapper.updateDishInfo(dish);
    }
}
